import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { 
  Table, Card, Button, Layout, Menu, Typography, 
  message, Image, Input, Select, Space 
} from 'antd';
import { 
  UserOutlined, LogoutOutlined, 
  FileImageOutlined, DownloadOutlined, ArrowLeftOutlined 
} from '@ant-design/icons';
import { getCustomerDetail, updatePhoto } from '../api/adminApi';
import { getCustomerPhotos, updatePhotoStatus } from '../api/photoApi';

const { Header, Content, Footer } = Layout;
const { Title } = Typography;

const MerchantCustomerDetail = () => {
  const { customerId } = useParams();
  const [customer, setCustomer] = useState(null);
  const [photos, setPhotos] = useState([]);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 检查登录状态并加载数据
  useEffect(() => {
    const token = localStorage.getItem('token');
    const user = JSON.parse(localStorage.getItem('user') || '{}');
    
    if (!token || user.role !== 'merchant') {
      message.error('请先登录商家账号');
      navigate('/login');
      return;
    }
    
    if (customerId) {
      fetchCustomerDetails();
      fetchCustomerPhotos();
    }
  }, [customerId, navigate]);

  // 获取客户详情
  const fetchCustomerDetails = async () => {
    try {
      const data = await getCustomerDetail(customerId);
      setCustomer(data);
    } catch (error) {
      console.error('获取客户信息失败:', error);
      message.error('获取客户信息失败');
    }
  };

  // 获取客户照片
  const fetchCustomerPhotos = async () => {
    setLoading(true);
    try {
      const data = await getCustomerPhotos(customerId);
      if (Array.isArray(data)) {
        setPhotos(data);
      }
    } catch (error) {
      console.error('获取照片失败:', error);
      message.error('获取客户照片失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理退出登录
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    navigate('/login');
    message.success('已退出登录');
  };

  // 更新照片状态
  const handleUpdateStatus = async (photoId, status) => {
    try {
      await updatePhotoStatus(photoId, status);
      message.success('状态更新成功');
      fetchCustomerPhotos();
    } catch (error) {
      console.error('更新状态失败:', error);
      message.error('更新照片状态失败');
    }
  };

  // 更新照片备注
  const handleUpdateRemark = async (photoId, status, remark) => {
    try {
      await updatePhoto(photoId, status, remark);
      message.success('备注更新成功');
      fetchCustomerPhotos();
    } catch (error) {
      console.error('更新备注失败:', error);
      message.error('更新照片备注失败');
    }
  };

  // 返回客户列表
  const goBack = () => {
    navigate('/merchant/customers');
  };

  // 返回照片管理
  const navigateToHome = () => {
    navigate('/merchant');
  };

  // 渲染照片预览
  const renderFilePreview = (url) => {
    return (
      <Image
        src={url}
        alt="照片"
        style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }}
        preview={{ src: url }}
      />
    );
  };

  // 表格列定义
  const columns = [
    {
      title: '照片',
      dataIndex: 'imageUrl',
      key: 'imageUrl',
      render: (url) => renderFilePreview(url),
      width: 80,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      render: (text, record) => (
        <Input
          defaultValue={text}
          onBlur={e => handleUpdateRemark(record._id, record.status, e.target.value)}
          style={{ width: 120 }}
        />
      ),
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => (
        <Select
          defaultValue={status}
          style={{ width: 100 }}
          onChange={value => handleUpdateStatus(record._id, value)}
        >
          <Select.Option value="待处理">待处理</Select.Option>
          <Select.Option value="已处理">已处理</Select.Option>
          <Select.Option value="已打印">已打印</Select.Option>
        </Select>
      ),
      width: 120,
    },
    {
      title: '上传时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: t => new Date(t).toLocaleString(),
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            icon={<DownloadOutlined />}
            onClick={() => window.open(record.imageUrl)}
          >下载</Button>
        </Space>
      ),
      width: 80,
    },
  ];

  return (
    <Layout className="layout" style={{ minHeight: '100vh' }}>
      <Header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div className="logo">
          <Title level={4} style={{ color: 'white', margin: 0 }}>YYB照片打印系统</Title>
        </div>
        <Menu theme="dark" mode="horizontal" selectedKeys={['customers']}>
          <Menu.Item key="photos" icon={<FileImageOutlined />} onClick={navigateToHome}>
            照片管理
          </Menu.Item>
          <Menu.Item key="customers" icon={<UserOutlined />}>
            客户管理
          </Menu.Item>
          <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
            退出登录
          </Menu.Item>
        </Menu>
      </Header>
      
      <Content style={{ padding: '50px' }}>
        <Button 
          type="primary" 
          icon={<ArrowLeftOutlined />} 
          onClick={goBack}
          style={{ marginBottom: 16 }}
        >
          返回客户列表
        </Button>
        
        <Card 
          title={customer ? `客户: ${customer.username}` : '客户详情'} 
          style={{ marginBottom: 16 }}
        >
          <Table
            rowKey="_id"
            columns={columns}
            dataSource={photos}
            loading={loading}
            pagination={{ pageSize: 10 }}
            scroll={{ x: 900 }}
          />
        </Card>
      </Content>
      
      <Footer style={{ textAlign: 'center' }}>
        YYB照片打印系统 ©{new Date().getFullYear()} 商家端
      </Footer>
    </Layout>
  );
};

export default MerchantCustomerDetail; 